<?php

namespace App\Wxapp\Controllers;

use App\Store\Models\Member\Member;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Wxapp\WxappSetting;
use EasyWeChat\MiniApp\Application;
use Illuminate\Support\Facades\Redis;

class BaseController extends Controller
{
    public $cp_id;
    public $meminfo;
    public $wxsetting;
    public $wxapp;

    /**
     * @param Request $request
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function __construct(Request $request)
    {
        //echo 3333;exit;
        $this->cp_id=$request->header('cpid')??0;
        $token = $request->header('token')?? '';
        $meminfo = Redis::get($token);
        $meminfo = $meminfo ? json_decode($meminfo, true) : [];

        if (!empty($meminfo)) {
            $member = Member::query()
                ->where('cp_id',$this->cp_id)
                ->where('is_del',1)
                ->where('id',$meminfo['id'])
                ->first();
             //控制器中间件
            $member =empty($member)?[] :$member->toArray();
             $this->middleware(function ($request, $next) use ($member) {
                 if(empty($member)||empty($member['wx_app_open_id'])){
                     return response()->json(['code' => '401', 'msg' => '用户信息存在,请重新授权']);
                 }else{
                     return $next($request);
                 }
             });


            $this->meminfo = $member;

        } else {
            $this->meminfo = [];
        }

        $wxsetting=WxappSetting::where('cp_id',$this->cp_id)->first();

        if(!empty($wxsetting)){
            $this->wxsetting=$wxsetting;
            $config = [
                'app_id' => $this->wxsetting->appid,
                'secret' => $this->wxsetting->appsecret,
            ];
            $this->wxapp = new Application($config);
        }

    }
    public function getAccessToken()
    {
        $accessToken = $this->wxapp->getAccessToken();
        $token=$accessToken->getToken();
        return $token;
    }

    public function getLoginToken($meminfo){
        $token=md5($meminfo->id.mt_rand(1000,9999).time().mt_rand(1000,9999));
        Redis::set($token,json_encode($meminfo));
        return $token;
    }
}
